const express = require('express');
const mongoose = require('mongoose');
const Good = require('../models/Good');
const User = require('../models/User');
require('../utils/util');
mongoose.connect('mongodb://localhost/vuemall');

mongoose.connection.on('connected',function(){
    console.log('MongoDB connected success');
});
mongoose.connection.on('error',function(){
    console.log('MongoDB connected failed');
});
mongoose.connection.on('disconnected',function(){
    console.log('MongoDB connected disconnected');
});
var router = express.Router();

router.get('/list',(req,res,next)=>{
    Good.find({},(err,data)=>{
        if(err){
            res.json({
                status:'1',
                msg:err.message
            });
        }else{
            //console.log(data);
            res.json({
                status:'0',
                msg:'',
                result:{
                    count:data.length,
                    list:data
                }
            });
        }
    });
});
//  分页
router.get("/getGoodsSort",(req,res,next)=>{
    let page = parseInt(req.query.page);
    let pageSize = parseInt(req.query.pageSize);
    let sort = req.query.sort;
    let check = req.query.check;
    var priceGt='', priceLte='';
    let skip = (page-1)*pageSize;
    var param;
    if(check != "0"){
        switch(check){
            case '1': priceGt=0;priceLte =100;break;
            case '2': priceGt=100;priceLte =500;break;
            case '3':priceGt=500;priceLte =1000;break;
            case '4':priceGt=1000;priceLte =5000;break;
        }
        param = {salePrice:{$gt:priceGt,$lte:priceLte}};
    }else{
        param = {};
    }
    let goodModel = Good.find(param).skip(skip).limit(pageSize);  //跳过八条数据
    goodModel.sort({'salePrice':sort}); // 按价格排序
    goodModel.exec((err,data)=>{
        if(err){
            res.json({
                status:'1',
                msg:err.message
            });
        }else{
            res.json({
                status:'0',
                msg:'',
                result:{
                    count:data.length,
                    list:data
                }
            });
        }
    });
});
router.post('/goods/addCart',(req,res,next)=>{
    var userId = req.cookies.userId;
    var productId = req.body.productId;
    User.findOne({userId:userId},(err1,userData)=>{
        if(err1){
            res.json({
                status:'1',
                msg:err1.message
            });
        }else{
            if(userData){
                var productItem;
                userData.cartList.forEach((item)=>{
                    if(item.productId == productId ){
                        item.productNum++;
                        productItem = item;
                    }
                });
                //console.log(productItem);
                if(productItem){
                    userData.save((err4,data)=>{
                        if(err4){
                            res.json({
                                status:'1',
                                msg:err4.message
                            });
                        }else{
                            res.json({
                                status:"0",
                                msg:'',
                                result:'suc',
                            });
                        }
                    });
                    
                }else{
                    Good.findOne({productId:productId},(err2,prodata)=>{
                        console.log(prodata);
                        if(err2){
                            res.json({
                                status:'1',
                                msg:err2.message
                            });
                        }else{
                            if(prodata){
                                //var newcart = {productNum:1,checked:1};
                                //let ab = Object.assign(prodata, newcart);
                                var ab = {
                                    productId:prodata.productId,
                                    productName:prodata.productName,
                                    salePrice:prodata.salePrice,
                                    productImage:prodata.productImage,
                                    checked:true,
                                    productNum:1,
                                }
                                //prodata.productNum = 1;
                                //prodata.checked = 1;
                                //console.log(ab);
                                userData.cartList.push(ab);
                                //console.log(prodata)
                                userData.save((err3,data)=>{
                                    if(err3){
                                        res.json({
                                            status:'1',
                                            msg:err3.message
                                        });
                                    }else{
                                        res.json({
                                            status:"0",
                                            msg:'',
                                            result:'suc',
                                        });
                                    }
                                });
                            }
                        }
                    });
                }
            }else{
                res.json({
                    status:"1",
                    msg:'请先登录注册',
                });
            }
        }
    });
});
router.post('/user/login',(req,res,next)=>{
    //console.log(req.body);
    var param = {
        userName:req.body.username,
        userPwd:req.body.password,
    };
    User.findOne(param,(err,data)=>{
        //console.log(data)
        if(err){
            res.json({
                status:'1',
                msg:err.message
            })
        }else{
            if(data){
                res.cookie("userId",data.userId,{
                    path:'/',
                    maxAge:1000*60*60
                });
                res.cookie("userName",data.userName,{
                    path:'/',
                    maxAge:1000*60*60
                });
                res.json({
                    status:'0',
                    msg:'',
                    result:{
                        username:data.userName,
                        userId:data.userId
                    }
                });
            }
        }
    })
});
router.post('/user/logout',(req,res,next)=>{
    res.cookie("userId","",{
        path:'/',
        maxAge:-1
    });
    res.cookie("userName","",{
        path:'/',
        maxAge:-1
    });
    res.json({
        status:'0',
        msg:'',
        result:{

        }
    });
});
router.post('/checkLogin',(req,res,next)=>{
    if(req.cookies.userId){
        res.json({
            status:'0',
            msg:'',
            result:{
                userName:req.cookies.userName,
                userId:req.cookies.userId
            }
        });
    }else{
        res.json({
            status:'1',
            msg:'未登录',
            result:''
        });
    }
});
router.post('/getUserId',(req,res,next)=>{
    res.json({
        status:'0',
        msg:'',
        result:{
            userName:req.cookies.userName,
            userId:req.cookies.userId
        }
    });
});
router.get('/getCartList',(req,res,next)=>{
    const userId = req.cookies.userId;
    User.findOne({userId:userId},(err,data)=>{
        //console.log(data);
        if(err){
            res.json({
                status:'1',
                msg:err.message
            });
        }else{
            if(data){
                res.json({
                    status:'0',
                    msg:'',
                    result:data.cartList,
                });
            }
        }
    });
});
router.post('/deleteProduct',(req,res,next)=>{
    const productId = req.body.productId;
    const userId = req.cookies.userId;
    User.update({userId:userId},{$pull:{'cartList':{'productId':productId}}},(err,data)=>{
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
           res.json({
               status:'0',
               msg:'',
               result:'suc'
           });
        }
    });
});
router.post('/changeNum',(req,res,next)=>{
    const productId = req.body.productId;
    const userId = req.cookies.userId;
    const productNum = req.body.productNum;
    console.log(productNum,productId,userId);
    User.updateOne({"userId":userId,"cartList.productId":productId},{'cartList.$.productNum':productNum},(err,data)=>{
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
            res.json({
                status:'0',
                msg:'',
                result:'suc'
            });
        }
    });
});
router.post('/changeCheck',(req,res,next)=>{
    const productId = req.body.productId;
    const userId = req.cookies.userId;
    const checked = req.body.checked;
    //console.log(productNum,productId,userId);
    User.updateOne({"userId":userId,"cartList.productId":productId},{'cartList.$.checked':checked},(err,data)=>{
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
            res.json({
                status:'0',
                msg:'',
                result:'suc'
            });
        }
    });
});
router.get('/getAddress',(req,res,next)=>{
    const userId = req.cookies.userId;
    User.findOne({userId:userId},(err,data)=>{
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
            if(data){
                res.json({
                    status:'0',
                    msg:'',
                    result:data.addressList,
                });
            }
        }
    });
});
router.post('/setDefault',(req,res,next)=>{
    const userId = req.cookies.userId;
    const addressId = req.body.addressId;
    User.findOne({userId:userId},(err,data)=>{
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            })
        }else{
            if(data){
                data.addressList.forEach((item)=>{
                    if(item.addressId == addressId){
                        item.isDefault = true;
                    }else{
                        item.isDefault = false;
                    }
                });
                data.save((err1,data)=>{
                    if(err1){
                        res.json({
                            status:'1',
                            msg:err.message,
                            result:''
                        })
                    }else{
                        res.json({
                            status:'0',
                            msg:'',
                            result:'suc',
                        })
                    }
                })
            }
        }
    })
});
router.post('/deleteAddress',(req,res,next)=>{
    const addressId = req.body.addressId;
    const userId = req.cookies.userId;
    console.log(addressId);
    User.update({userId:userId},{$pull:{'addressList':{'addressId':addressId}}},(err,data)=>{
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
           res.json({
               status:'0',
               msg:'',
               result:'suc'
           });
        }
    });
});
router.get('/getOrderList',(req,res,next)=>{
    const userId = req.cookies.userId;
    User.findOne({userId:userId},(err,data)=>{
        //console.log(data);
        if(err){
            res.json({
                status:'1',
                msg:err.message
            });
        }else{
            if(data){
                var orderList = [];
                data.cartList.forEach((item)=>{
                    if(item.checked){
                        orderList.push(item);
                    }
                });
                res.json({
                    status:'0',
                    msg:'',
                    result:orderList,
                });
            }
        }
    });
});
router.post('/createOrder',(req,res,next)=>{
    const userId = req.cookies.userId;
    const totalPrice = req.body.totalPrice;
    const addressId = req.body.addressId;
    User.findOne({userId:userId},(err,data)=>{
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
            if(data){
                var addressInfo;
                var goodList = [];
                data.addressList.forEach((item)=>{
                    if(item.addressId = addressId){
                        addressInfo = item;
                    }
                });
                data.cartList.filter((item)=>{
                    if(item.checked){
                        goodList.push(item);
                    }
                });
                var platform = '622';
                var r1 = Math.floor(Math.random()*10);
                var r2 = Math.floor(Math.random()*10);
                var sysData = new Date().Format('yyyyMMddhhmmss');
                var createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
                var orderId = platform+r1+sysData+r2;
                var order = {
                    orderId:orderId,
                    orderTotal:totalPrice,
                    addressInfo:addressInfo,
                    goodList:goodList,
                    orderStatus:'1',
                    createDate:createDate
                }
                data.orderList.push(order);
                data.save((err1,data)=>{
                    if(err){
                        res.json({
                            status:'1',
                            msg:err.message,
                            result:''
                        });
                    }else{
                        res.json({
                            status:'0',
                            msg:'',
                            result:{
                                order:order.orderId,
                                orderTotal:totalPrice
                            }
                        })
                    }
                })
            }
        }
    })
});
router.post('/getOrder',(req,res,next)=>{
    var order = req.body.orderId;
    var userId = req.cookies.userId;
    User.findOne({userId:userId},(err,data)=>{
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
            var orderItem;
            if(data){
                data.orderList.forEach((item)=>{
                    if(item.orderId == order){
                        orderItem = item;
                    }
                });
                res.json({
                    status:'0',
                    msg:'',
                    result:orderItem,
                })
            }
        }
    });
});
router.get('/getCartNum',(req,res,next)=>{
    const userId = req.cookies.userId;
    User.findOne({userId:userId},(err,data)=>{
        if(err){
            res.json({
                status:'1',
                msg:err.message,
                result:''
            });
        }else{
            var itemNum = 0;
            if(data){
                data.cartList.forEach((item)=>{
                    itemNum += parseFloat(item.productNum) ;
                });
                res.json({
                    status:'0',
                    msg:'',
                    result:itemNum,
                })
            }
        }
    })
})
module.exports = router;
